import React, { useEffect, useRef, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './TableColumns'
import { DashboardSaleVO as ITableData } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import { getAllProductColorGroup, getProductClassConfigByType } from '@/api/goods'
import { getDashboardSpuSale, exportListDashboardSpuSale, getQuotationSearchCondition } from '@/api/dashboard'
import { exportNotification, getRecentSeventDays } from '@/utils/util'
import PermissionButton from '@/components/PermissionButton'
import { QuestionCircleOutlined, UploadOutlined } from '@ant-design/icons'
import { Checkbox, Form, Modal, Spin, Tooltip } from 'antd'
import useModal from '@/hooks/useModal'
import { EditFormVertical } from '@/components/QsfCustomForm'
import { useFormExport } from './FormConfig'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [colorGroupIdOptions, setcolorGroupIdOptions] = useState<IOptionItem[]>([])
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { setCachePage, getCachePage } = useCachePage()
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<any[]>([])
  const defaultDateRange = getRecentSeventDays('YYYY-MM-DD')
  const [spinning, setspinning] = useState(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [midClass, setmidClass] = useState<IOptionItem[]>([])
  const [smallClass, setsmallClass] = useState<IOptionItem[]>([])
  const [tinyClass, settinyClass] = useState<IOptionItem[]>([])
  const [expand, setexpand] = useState(false)
  const SalesExportModal = useModal({
    onSuccess: async (res) => {
      if (res?.code === 200 && res?.data) {
        await exportNotification(res?.data, navigate).finally(() => setspinning(false))
      }
    },
    onFail: () => setspinning(false),
  })
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getDashboardSpuSale, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      saleStartDate: defaultDateRange,
      branchOffice: '直营',
      queryMainProduct: ['queryMainProduct'],
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqestParams) => {
      const { pageRange, queryMainProduct, expand, ...reqParams } = reqestParams
      return {
        ...reqParams,
        saleStartDate:
          reqParams.saleStartDate && reqParams.saleStartDate.length === 2 ? reqParams.saleStartDate[0] : null,
        saleEndDate:
          reqParams.saleStartDate && reqParams.saleStartDate.length === 2 ? reqParams.saleStartDate[1] : null,
        pageRange: pageRange && pageRange.length > 0 ? 'SKC' : null,
        queryMainProduct: queryMainProduct && queryMainProduct.length > 0 ? true : null,
      }
    },
  })
  useEffect(() => {
    // getProductClassConfig()
    getOptions()
    getAllColorGroup()
    handleCacheData()
  }, [])
  useEffect(() => {
    if (expand) {
      const ids = tableProps?.dataSource?.map(
        (rows) =>
          rows?.id + '_' + rows?.spuCode + '_' + rows?.dataType + '_' + rows?.fineClassName + '_' + rows?.colorName,
      )
      setexpandedRowKeys(ids)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      if (cacheData?.expand) setexpand(!!cacheData?.expand)
      const { SupplierOption, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      reload({ ...resetCacheData })
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.className,
          bigClassId: item.classConfigId,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const onBigClassIdChange = (_: string, item: any) => {
    const bigClassId = item?.bigClassId || null
    bigClassId && getOptions(bigClassId)
    form.setFieldsValue({
      smallClassNameList: null,
      fineClassNameList: null,
    })
  }
  const onBigClassIdClear = () => {
    form.setFieldsValue({
      smallClassNameList: null,
      fineClassNameList: null,
    })
    setsmallClass([])
    settinyClass([])
  }
  const getOptions = async (bigClassId?: string) => {
    const res = await getQuotationSearchCondition({ bigClassId })
    if (res.code == 200) {
      if (bigClassId === undefined) {
        if (res.data.bigClassList && res.data.bigClassList.length > 0) {
          setclassBig(
            res.data?.bigClassList?.map((item: any) => {
              return {
                label: item.className,
                value: item.className,
                bigClassId: item.classConfigId,
              }
            }),
          )
        }
        if (res.data.midClassList && res.data.midClassList.length > 0) {
          setmidClass(res.data.midClassList)
        }
        return
      }
      if (res.data.smallClassList && res.data.smallClassList.length > 0) {
        setsmallClass(res.data.smallClassList)
      }
      if (res.data.tinyClassList && res.data.tinyClassList.length > 0) {
        settinyClass(res.data.tinyClassList)
      }
    }
  }
  const getAllColorGroup = async () => {
    const res = await getAllProductColorGroup<{
      colorGroupName: string
      colorGroupId: string
      colorGroupCode: string
    }>()
    if (res.code === 200) {
      const data = res?.data?.map((item) => {
        return {
          label: item.colorGroupName,
          value: item.colorGroupId,
        }
      })
      setcolorGroupIdOptions(data)
    }
  }
  return (
    <PageContainer className="dashboard_sales_wrap">
      <SearchForm
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfig({
          SupplierOption,
          handleSearchSupplier,
          classBig,
          DICTDATA,
          colorGroupIdOptions,
          onBigClassIdChange,
          onBigClassIdClear,
          midClass,
          smallClass,
          tinyClass,
          form,
        })}
        onFinish={async () => {
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          reset()
          setCachePage({
            current: 1,
            size: 10,
            saleStartDate: defaultDateRange,
            branchOffice: '直营',
            queryMainProduct: ['queryMainProduct'],
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <Form form={form}>
                <Form.Item noStyle name="queryMainProduct">
                  <Checkbox.Group
                    disabled={tableProps.loading}
                    onChange={(queryMainProduct) => {
                      const cacheData = getCachePage()
                      setCachePage({
                        ...cacheData,
                        queryMainProduct,
                        current: 1,
                      })
                      search()
                    }}
                    options={[
                      {
                        label: (
                          <div>
                            查看最新一周的主力商品
                            <span style={{ marginLeft: 4, cursor: 'pointer' }}>
                              <Tooltip placement="top" title={'同期内销售额Top100的款'}>
                                <QuestionCircleOutlined />
                              </Tooltip>
                            </span>
                          </div>
                        ),
                        value: 'queryMainProduct',
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
              <Checkbox.Group
                value={expand ? ['color'] : undefined}
                disabled={tableProps.loading}
                onChange={(vals) => {
                  const expand = !!vals?.includes('color')
                  setexpand(expand)
                  const cacheData = getCachePage()
                  setCachePage({
                    ...cacheData,
                    expand,
                  })
                }}
                options={[
                  {
                    label: '展开到颜色',
                    value: 'color',
                  },
                ]}
              />
              <Form form={form}>
                <Form.Item noStyle name="pageRange">
                  <Checkbox.Group
                    disabled={tableProps.loading}
                    onChange={(pageRange) => {
                      const cacheData = getCachePage()
                      setCachePage({
                        ...cacheData,
                        pageRange,
                        current: 1,
                      })
                      search()
                    }}
                    options={[
                      {
                        label: '只看颜色',
                        value: 'pageRange',
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="dashboardSalesExport"
                icon={<UploadOutlined />}
                loading={SalesExportModal.confirmLoading}
                disabled={tableProps.loading}
                onClick={() => {
                  SalesExportModal.openModal()
                }}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        stripe={false}
        isAutoScrollY
        {...tableProps}
        columns={useIndexColumns({ navigate })}
        rowKey={(rows) =>
          rows?.id + '_' + rows?.spuCode + '_' + rows?.dataType + '_' + rows?.fineClassName + '_' + rows?.colorName
        }
        // rowSelection={{
        //   selectedRowKeys,
        //   onChange(selectedRowKeys, selectedRows) {
        //     setSelectedRowKeys(selectedRowKeys)
        //     setselectedRowInfos(selectedRows)
        //   },
        // }}
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys: any) => {
            setexpandedRowKeys(keys)
          },
        }}
      ></CustomTable>
      <Modal
        title="导出选项"
        maskClosable
        open={SalesExportModal.open}
        onCancel={SalesExportModal.closeModal}
        okText="导出"
        onOk={() => {
          setspinning(true)
          const { exportDataTypeList, ...retparams } = params
          SalesExportModal.handleSubmit(() =>
            exportListDashboardSpuSale({
              ...retparams,
              ...SalesExportModal.form.getFieldsValue(),
            }),
          )
        }}
        confirmLoading={SalesExportModal.confirmLoading}
      >
        <EditFormVertical
          editConfig={useFormExport()}
          form={SalesExportModal.form}
          initialValues={{
            exportDataTypeList: ['SPU', 'SKC'],
          }}
        />
      </Modal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
